﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using EKETEAM.FrameWork;
using EKETEAM.Data;
using EKETEAM.Tencent.WxWork;
using System.Web.Caching;
using System.Net;
using System.IO;
using System.Text;
using LitJson;


namespace eFrameWork.WXWork
{
    public partial class Login : System.Web.UI.Page
    {
        public string UserArea = "Application";
        eUser user;
        public string redirect_uri = "";

        private void ProxyLogin()
        {
            if (Request.QueryString["data"] != null)
            {
                #region 代理返回数据
                string data = Request.QueryString["data"].ToString();
                try
                {
                    string base64 = Base64.Decode(data);
                    if (base64.StartsWith("{"))
                    {
                        JsonData json = JsonMapper.ToObject(base64);
                        string qyuserid = json.GetValue("UserId");
                        if (qyuserid.Length == 0)
                        {
                            Response.Write("登录失败,请与企业微信管理员联系!");
                            Response.End();
                        }
                        DataTable tb = eBase.UserInfoDB.getDataTable("select top 1 * from a_eke_sysUsers where qyUserID='" + qyuserid + "' and delTag=0 order by LEN(ISNULL(qyUserID,'')) desc, addTime");
                        if (tb.Rows.Count > 0)
                        {
                            #region 数据库存在该用户
                            if (tb.Rows[0]["Active"].ToString() == "False")
                            {
                                Response.Write("登录失败,用户信息已停用!");
                                Response.End();
                            }
                            if (tb.Rows[0]["delTag"].ToString() == "True")
                            {
                                Response.Write("登录失败,用户信息已删除!");
                                Response.End();
                            }
                            user = new eUser(UserArea);
                            eFHelper.saveUserInfo(user, tb.Rows[0]); //保存用户登录信息
                            eFHelper.UserLoginLog(user); //用户登录日志
                            string fromurl = eParameters.QueryString("fromURL");
                            if (fromurl.Length == 0)
                            {
                                Response.Redirect("Default.aspx", true);
                            }
                            else
                            {
                                Response.Redirect(HttpUtility.UrlDecode(fromurl), true);
                            }
                            #endregion
                        }

                    }                    
                    Response.End();
                }
                catch
                {
                }
                #endregion
            }
            string self_url = HttpUtility.UrlEncode(Request.Url.AbsoluteUri);
            string url = eBase.WXWorkAccount.getValue("Proxy") + "WXWork/loginProxy.aspx?fromURL=" + self_url;
            Response.Redirect(url, true);
            //eBase.Writeln(url);
            //eBase.End();
        }
        protected void Page_Load(object sender, EventArgs e)
        {

            if (eBase.WXWorkAccount.getValue("Proxy").Length > 0)
            {
                ProxyLogin();
                return;
            }
            if (eBase.WXWorkAccount.getValue("CorpID").Length == 0 || eBase.WXWorkAccount.getValue("AgentId").Length == 0 || eBase.WXWorkAccount.getValue("Secret").Length == 0)
            {
                Response.Write("没有绑定域名、企业微信或绑定信息不完整!");
                Response.End();
            }

            eFileInfo fi = new eFileInfo(Request.Url.PathAndQuery);    
            string folderPath = fi.Path;
            string fromURL = eParameters.QueryString("fromURL");//登录来源页面URL
            user = new eUser(UserArea);
            if (user.Logined)
            {
                return;
            }

            //redirect_uri = Request.Url.Scheme + "://" + Request.Url.Host;
            //redirect_uri += (Request.Url.Port == 80 || Request.Url.Port == 443 ? "" : ":" + Request.Url.Port.ToString()) + folderPath + "Login.aspx";

            redirect_uri = Request.Url.Scheme + "://" + eRequest.fromHost;
            redirect_uri += (eRequest.fromPort == 80 || eRequest.fromPort == 443 ? "" : ":" + eRequest.fromPort.ToString()) + folderPath + "Login.aspx";

            if (fromURL.Length > 0) redirect_uri += "?fromURL=" + HttpUtility.UrlEncode(HttpUtility.UrlEncode(fromURL)); // HttpUtility.UrlDecode(fromURL);
            redirect_uri = HttpUtility.UrlEncode(redirect_uri);


            string code = Request["code"];
            if (string.IsNullOrEmpty(code))
            {
                OpenAccess();
            }

            JsonData json = WxWorkHelper.getUserInfo(code);
            string qyuserid = json.GetValue("UserId"); //非企业成员 返回OpenId ，这里为空
            string userticket = json.GetValue("user_ticket");
            if (qyuserid.Length == 0)
            {
                string msg = json.getValue("errmsg");
                if (msg.Length == 0) msg = "登录失败,请与企业微信管理员联系!";
                Response.Write(msg);
                Response.End();
            }

            DataTable tb = eBase.UserInfoDB.getDataTable("select top 1 * from a_eke_sysUsers where qyUserID='" + qyuserid + "' and delTag=0 order by LEN(ISNULL(qyUserID,'')) desc, addTime");
            if (tb.Rows.Count > 0)
            {
                #region 数据库存在该用户
                if (tb.Rows[0]["Active"].ToString() == "False")
                {
                    Response.Write("登录失败,用户信息已停用!");
                    Response.End();
                }
                if (tb.Rows[0]["delTag"].ToString() == "True")
                {
                    Response.Write("登录失败,用户信息已删除!");
                    Response.End();
                }
                user = new eUser(UserArea);
                eFHelper.saveUserInfo(user, tb.Rows[0]); //保存用户登录信息
                eFHelper.UserLoginLog(user); //用户登录日志
                Response.Redirect(HttpUtility.UrlDecode(fromURL), true);
                #endregion
            }
            else
            {
                #region 添加用户
                JsonData _json = WxWorkHelper.getUserDetail(userticket);
                string avatar= _json.GetValue("avatar").Replace("\\", "");
                int mode = 2;//1.自动添加用户，2.让用户选择绑定现有帐号，或注册新帐号。
                if (mode == 1) //1.自动添加用户
                {
                    #region 自动添加用户
                    eTable etb = new eTable("a_eke_sysUsers");
                    etb.DataBase = eBase.UserInfoDB;
                    if (eBase.WXWorkAccount.getValue("SiteID").Length > 0) etb.Fields.Add("SiteID", eBase.WXWorkAccount.getValue("SiteID"));
                    etb.Fields.Add("UserType", "2");
                    etb.Fields.Add("qyUserID", qyuserid);
                    etb.Fields.Add("xm", _json.GetValue("name"));
                    etb.Fields.Add("name", _json.GetValue("name"));
                    etb.Fields.Add("gender", _json.GetValue("gender"));
                    etb.Fields.Add("avatar", avatar);
                    etb.Fields.Add("RoleID", "201310aa-89d7-4209-b3c1-b507e1dc6267"); //默认具有角色的权限
                    etb.Add();
             
                    string userid = etb.ID;
                    string face = downHeadImage(userid, qyuserid, avatar);
                    tb = eBase.UserInfoDB.getDataTable("select top 1 * from a_eke_sysUsers where UserID='" + userid + "'");
                    if (tb.Rows.Count > 0)
                    {
                        user = new eUser(UserArea);
                        eFHelper.saveUserInfo(user, tb.Rows[0]); //保存用户登录信息
                    }
                    eFHelper.UserLoginLog(user); //用户登录日志
                    Response.Redirect(HttpUtility.UrlDecode(fromURL), true);
                    #endregion
                }
                else //让用户选择绑定现有帐号，或注册新帐号。
                {


                    JsonData jd = new JsonData();
                    jd["userid"] = qyuserid;
                    jd["name"] = _json.GetValue("name");
                    jd["gender"] = _json.GetValue("gender");
                    jd["avatar"] = avatar;
                    jd["fromURL"] = fromURL;
                    Session["WXWork_UserInfo"] = jd.ToJson();
                    Response.Redirect("BindChoose.aspx", true);
                }
                #endregion
            }
        }
        private string downHeadImage(string UserID, string qyUserID, string url)
        {
            string siteid = eBase.WXWorkAccount.getValue("SiteID");

            string basePath = HttpContext.Current.Server.MapPath("~/upload/" + (siteid.Length > 0 ? siteid + "/" : "") + "face/");
            if (!Directory.Exists(basePath)) Directory.CreateDirectory(basePath);

            string face = "upload/" + (siteid.Length > 0 ? siteid + "/" : "") + "face/" + UserID + "_" + qyUserID + ".jpg";

            string headpath = HttpContext.Current.Server.MapPath("~/" + face);
            WebClient wc = new WebClient();
            try
            {
                if (!File.Exists(headpath))
                {
                    wc.DownloadFile(url, headpath);
                    wc.Dispose();
                }
                eBase.UserInfoDB.Execute("update a_eke_sysUsers set face='" + face + "' where userid='" + UserID + "'");

            }
            catch
            {

            }
            return face;
        }
        

        private void OpenAccess()
        {   
            if (!user.Logined)
            {
                string url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base&agentid={2}&state=STATE#wechat_redirect", eBase.WXWorkAccount.getValue("CorpID"), redirect_uri, eBase.WXWorkAccount.getValue("AgentId"));
                url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_userinfo&agentid={2}&state=STATE#wechat_redirect", eBase.WXWorkAccount.getValue("CorpID"), redirect_uri, eBase.WXWorkAccount.getValue("AgentId"));
                Response.Redirect(url);
            }
            else
            {
                Response.Redirect(Request.Url.ToString());
            }
        }
    
    }
}